const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const config = require('../config');

// Ensure upload directory exists
if (!fs.existsSync(config.server.uploadDir)) {
  fs.mkdirSync(config.server.uploadDir, { recursive: true });
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, config.server.uploadDir),
  filename: (req, file, cb) => {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
    const fileNameWithoutExt = path.basename(file.originalname, path.extname(file.originalname));
    cb(null, `${fileNameWithoutExt}-${uniqueSuffix}${path.extname(file.originalname)}`);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: config.upload.maxFileSize },
  fileFilter: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    if (config.upload.allowedFileTypes.includes(ext)) {
      cb(null, true);
    } else {
      cb(new Error('Only .apk files are allowed'), false);
    }
  }
});

router.post('/apkupload', upload.single('file'), (req, res) => {
  try {
    if (!req.file) {
      return res.status(200).json({
        code: '0',
        data: {},
        msg: 'No file uploaded'
      });
    }

    const fileName = req.file.filename;
    res.status(200).json({
      code: '0',
      data: {
        filename: fileName,
        url: `${config.server.urlDir}${fileName}`
      },
      msg: 'File uploaded successfully'
    });
  } catch (error) {
    console.error('Upload error:', error);
    res.status(200).json({
      code: '0',
      data: {},
      msg: error.message || 'File upload failed'
    });
  }
});

module.exports = router; 